# -*- coding: utf-8 -*-
import logging

from django.conf import settings
from qiniu import Auth, BucketManager, build_batch_delete

_LOGGER = logging.getLogger(__name__)
EXPIRE_TIME = 365 * 24 * 3600  # 1 year


def get_token(bucket=settings.ADMIN_BUCKET_NAME, expires=EXPIRE_TIME):
    Q = Auth(*(settings.QINIU_KEY_PAIR))
    token = Q.upload_token(bucket, expires=expires)

    return token


def delete_data_by_url(urls, bucket=settings.ADMIN_BUCKET_NAME, key_prefix=''):
    keys = []
    for url in urls:
        if not url.endswith('/'):
            url += '/'
        key = url.split('/')[-2]
        if key_prefix:
            key = '%s/%s' % (key_prefix, key)
        keys.append(key)
    delete_data_by_key(keys, bucket)


def delete_data_by_key(keys, bucket):
    Q = Auth(*(settings.QINIU_KEY_PAIR))
    ops = build_batch_delete(bucket, keys)
    b = BucketManager(Q)
    b.batch(ops)
